# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import logging
import random
import time
from urllib.parse import urlparse
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.response import response_status_message


class RandomDelayMiddleware:
    """随机延迟中间件，为每个请求添加随机延迟"""
    
    def __init__(self, delay_min, delay_max):
        self.delay_min = delay_min
        self.delay_max = delay_max
        self.logger = logging.getLogger(__name__)
    
    @classmethod
    def from_crawler(cls, crawler):
        # 从settings中获取延迟范围
        delay_min = crawler.settings.getfloat('RANDOM_DELAY_MIN', 1.0)
        delay_max = crawler.settings.getfloat('RANDOM_DELAY_MAX', 3.0)
        return cls(delay_min, delay_max)
    
    def process_request(self, request, spider):
        # 为请求添加随机延迟
        delay = random.uniform(self.delay_min, self.delay_max)
        self.logger.debug(f"添加随机延迟 {delay:.2f} 秒到 {request.url}")
        time.sleep(delay)


class CustomRetryMiddleware(RetryMiddleware):
    """自定义重试中间件，处理特定错误和状态码"""
    
    def __init__(self, settings):
        super().__init__(settings)
        self.logger = logging.getLogger(__name__)
    
    def process_response(self, request, response, spider):
        # 处理特定状态码
        if response.status in [403, 429]:
            self.logger.warning(f"收到 {response.status} 状态码，等待后重试: {request.url}")
            time.sleep(60)  # 等待60秒后重试
            reason = response_status_message(response.status)
            return self._retry(request, reason, spider) or response
        return super().process_response(request, response, spider)
    
    def process_exception(self, request, exception, spider):
        # 处理特定异常
        self.logger.error(f"请求异常: {exception.__class__.__name__}: {exception}")
        return super().process_exception(request, exception, spider)


class DomainFilterMiddleware:
    """域名过滤中间件，只允许爬取特定域名"""
    
    def __init__(self, allowed_domains):
        self.allowed_domains = allowed_domains
        self.logger = logging.getLogger(__name__)
    
    @classmethod
    def from_crawler(cls, crawler):
        # 从settings中获取允许的域名
        allowed_domains = crawler.settings.getlist('ALLOWED_DOMAINS', [])
        return cls(allowed_domains)
    
    def process_request(self, request, spider):
        # 检查请求的域名是否在允许列表中
        domain = urlparse(request.url).netloc
        if self.allowed_domains and domain not in self.allowed_domains:
            self.logger.warning(f"过滤非允许域名的请求: {domain} ({request.url})")
            raise IgnoreRequest(f"域名 {domain} 不在允许列表中")


class SpiderStatsMiddleware:
    """爬虫统计中间件，记录爬虫的统计信息"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.start_time = None
        self.item_count = 0
        self.request_count = 0
        self.error_count = 0
    
    @classmethod
    def from_crawler(cls, crawler):
        # 创建中间件实例
        middleware = cls()
        # 注册信号处理器
        crawler.signals.connect(middleware.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(middleware.spider_closed, signal=signals.spider_closed)
        crawler.signals.connect(middleware.item_scraped, signal=signals.item_scraped)
        crawler.signals.connect(middleware.request_scheduled, signal=signals.request_scheduled)
        crawler.signals.connect(middleware.spider_error, signal=signals.spider_error)
        return middleware
    
    def spider_opened(self, spider):
        self.start_time = time.time()
        self.logger.info(f"爬虫 {spider.name} 已启动")
    
    def spider_closed(self, spider, reason):
        elapsed = time.time() - self.start_time
        self.logger.info(f"爬虫 {spider.name} 已关闭，原因: {reason}")
        self.logger.info(f"运行时间: {elapsed:.2f} 秒")
        self.logger.info(f"请求数: {self.request_count}")
        self.logger.info(f"item数: {self.item_count}")
        self.logger.info(f"错误数: {self.error_count}")
    
    def item_scraped(self, item, response, spider):
        self.item_count += 1
        if self.item_count % 100 == 0:
            self.logger.info(f"已抓取 {self.item_count} 个items")
    
    def request_scheduled(self, request, spider):
        self.request_count += 1
        if self.request_count % 100 == 0:
            self.logger.info(f"已发送 {self.request_count} 个请求")
    
    def spider_error(self, failure, response, spider):
        self.error_count += 1
        self.logger.error(f"爬虫错误: {failure.value}")


class MyscraperSpiderMiddleware:
    """Scrapy默认的Spider中间件"""
    
    @classmethod
    def from_crawler(cls, crawler):
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s
    
    def process_spider_input(self, response, spider):
        return None
    
    def process_spider_output(self, response, result, spider):
        for i in result:
            yield i
    
    def process_spider_exception(self, response, exception, spider):
        pass
    
    def process_start_requests(self, start_requests, spider):
        for r in start_requests:
            yield r
    
    def spider_opened(self, spider):
        spider.logger.info(f"Spider opened: {spider.name}")


class MyscraperDownloaderMiddleware:
    """Scrapy默认的下载器中间件"""
    
    @classmethod
    def from_crawler(cls, crawler):
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s
    
    def process_request(self, request, spider):
        return None
    
    def process_response(self, request, response, spider):
        return response
    
    def process_exception(self, request, exception, spider):
        pass
    
    def spider_opened(self, spider):
        spider.logger.info(f"Spider opened: {spider.name}")
